package com.strong.system.constroller;

import cn.hutool.core.util.ObjUtil;
import jakarta.persistence.EntityNotFoundException;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import static com.strong.utils.security.SecurityUtils.SPRING_SECURITY_LAST_EXCEPTION;

/**
 * 系统异常控制器
 *
 * @author simen
 * @date 2022/02/17
 */
@Slf4j
@Controller
public class SystemController {

    @RequestMapping("/getPerson")
    @PreAuthorize("hasAuthority('file_read')")
    public String getPerson(HttpServletResponse response) throws Exception {
        System.out.println("getPerson");
        response.getWriter().println("getPerson getPerson");
        return "person";
    }

    @RequestMapping("/getPersonError")
    public String getPersonError() {
        System.out.println("getPersonError");
        throw new EntityNotFoundException();
    }

    @GetMapping("/login")
    public ModelAndView login(HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login");

        Exception e = (Exception) session.getAttribute(SPRING_SECURITY_LAST_EXCEPTION);
        if (ObjUtil.isNotNull(e)) {
            modelAndView.addObject("error", e.getMessage());
            e.printStackTrace();
        }
        return modelAndView;
    }

}
